import { getById, update } from '@/api/businessManage/dataLoader/spatialData'
import { resetAllForm } from '@/utils/ruoyi'

export default function () {
  const { proxy } = getCurrentInstance()
  const route = useRoute()
  const router = useRouter()
  const initForm = () => ({})
  const data = reactive({
    addDrawer: true,
    drawerLoading: false,
    provinceData: [],
    cityData: [],
    areaData: [],
    form: initForm()
  })
  const { addDrawer, drawerLoading, form } = toRefs(data)

  const openDrawer = () => {
    proxy.$refs['addRef'].clearValidate()
    drawerLoading.value = true
    const { detailId } = route.query
    let path = route.name
    if(/dataIntegrate|achievementSearch|quickMapping/.test(route.name)){
      path = route.name.split('-')[1]
    }
    getById(path, detailId).then(res => {
      drawerLoading.value = false
      form.value = res.data
    }).catch(err => {
      drawerLoading.value = false
    })
  }
  const closeDrawer = () => {
    resetAllForm(form.value, initForm())
    router.go(-1)
  }
  // 保存
  const confirmClick = () => {
    proxy.$refs.addRef.validate((valid, fields) => {
      if (valid) {
        update(route.name, { ...form.value }).then(res => {
          proxy.$modal.msgSuccess('修改成功！')
          resetAllForm(form.value, initForm())
          const { id, name, typeName } = route.query
          router.push({ path: `/businessManage/dataLoader/subject/spatialData`, query: { id, name, typeName } })
        })
      } else {
        proxy.$refs.addRef.scrollToField(Object.keys(fields)[0])
      }
    })
  }
  const uploadSuccess = (type, files) => {
    form.value[type + 'Id'] = files.map(item => item.attachId).join(',')
    proxy.$refs.addRef.clearValidate(type + 'Id')
  }

  const deleteFile = (type, files) => {
    form.value[type + 'Id'] = files.map(item => item.attachId).join(',')
  }

  const updateDict = (field, data) => {
    form.value[field] = data
  }

  const isShowSave = !/dataIntegrate|achievementSearch|quickMapping/.test(route.path)

  return {
    addDrawer, drawerLoading, form, typeName: route.query.typeName,
    openDrawer,
    closeDrawer,
    confirmClick,
    uploadSuccess,
    deleteFile,
    updateDict,
    route,
    isShowSave
  }
}
